﻿using System;
using System.Windows.Controls;
using System.Windows.Threading;
using Vkontakte.Api;
using Vkontakte.Api.Windows;

namespace VkClientIM.UI
{
	/// <summary>
	/// Interaction logic for Splash.xaml
	/// </summary>
	public partial class Splash : UserControl
	{
		private DispatcherTimer _timer;
		private Vkontakte.Api.Windows.AuthorizatorWinForms _auth;
		private object _mutex=new object();
		private Session _session;
		public Splash()
		{
			_auth = new AuthorizatorWinForms();
			_auth.AppID = VkClientIM.Windows.AuthenticationWindow.MyAppID;
			_auth.ApplicationAccess = ApplicationAccess.AllExceptAddLeft;
			_auth.Authenticated += auth_Authenticated;
			_auth.NeedLoginData += new Action(auth_NeedLoginData);
			_auth.Authenticate();
			InitializeComponent();
			_timer = new DispatcherTimer( TimeSpan.FromSeconds( 3 ),
			                              DispatcherPriority.Background,
										  OnTimer,
			                              this.Dispatcher );
			
		}

		void auth_NeedLoginData()
		{
			lock (_mutex)
			{
				if ( _timer != null )
				{
					_timer.Stop();
					_timer = null;
				}
			}
			InvokeSplashCompleted();
		}

		void auth_Authenticated()
		{
			lock (_mutex)
			{
				if (_timer != null)
				{
					_timer.Stop();
					_timer = null;
				}
			}
			_session= _auth.GetAuthorizationToken();
			InvokeSplashCompleted();
		}

		private void OnTimer(object sender,EventArgs args)
		{
			lock (_mutex)
			{
				if (_timer != null)
				{
					_timer.Stop();
					_timer = null;
				}
			}
			InvokeSplashCompleted();
		}

		private void InvokeSplashCompleted()
		{
			if (SplashCompleted != null)
			{
				SplashCompleted( this, new EventArgs() );
				SplashCompleted = null;
			}
		}

		public bool IsAuthenticated { get; internal set; }

		internal Session GetSession()
		{
			return _session;
		}

		public event EventHandler SplashCompleted;

		private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e)
		{
			if (_timer != null)
			{
				_timer.Start();
			}
		}
	}
}
